<?php

namespace App\Services\Goods;
use App\Exceptions\BusinessException;
use App\Common\ResponseCode;
use App\Models\Goods\Brand;
use App\Params\Backend\BrandListParams;
use App\Params\Backend\BrandUpdateParam;
use App\Services\BaseService;

/**
 * 商品品牌相关业务类
 *
 * @package App\Http\Services
 * @author WangBin
 * @date 2021-06/11
 */
class BrandService extends BaseService
{
    /**
     * 保存品牌
     *
     * @param BrandUpdateParam $data
     * @return mixed
     * @throws BusinessException
     */
    public function update(BrandUpdateParam $data)
    {
        if($data->getBrandId()) {
            $brand = Brand::getById($data->getBrandId());
            if(is_null($brand)) {
                throw new BusinessException(ResponseCode::BRAND_NOT_FOUND);
            }
        }
        // 校验品牌名称唯一
        $check = Brand::checkName($data->getName(), $data->getBrandId());
        if($check) {
            throw new BusinessException(ResponseCode::SAVE_FAIL, ['error' => '名称已存在']);
        }
        return Brand::saveData($data);
    }

    /**
     * 品牌列表
     *
     * @param BrandListParams $filter
     * @return array
     */
    public function getList(BrandListParams $filter)
    {
        $brands = Brand::getByFilter($filter);
        return $this->toList($brands, $filter->getPage(), $filter->getPageSize());
    }

    /**
     * 获取品牌详情
     *
     * @param int $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function get(int $id)
    {
        return Brand::getById($id);
    }
}